#pragma once
#include <queue>
#include <pthread.h>

// N 用于设置队列的最大容量
template <class T, size_t N>
class BlockQueue
{
public:
    BlockQueue()
    {
        pthread_mutex_init(&_lock, nullptr);
        pthread_cond_init(&_p_cond, nullptr);
        pthread_cond_init(&_c_cond, nullptr);
    }

    void push(const T &data)
    {
        pthread_mutex_lock(&_lock);
        while(_q.size() == maxCap)
        {
            pthread_cond_wait(&_p_cond, &_lock);
        }
        _q.push(data);
        if (_q.size() > high_water)
            pthread_cond_broadcast(&_c_cond);
        pthread_mutex_unlock(&_lock);
    }

    T pop()
    {
        pthread_mutex_lock(&_lock);
        while (_q.size() == 0)
        {
            pthread_cond_wait(&_c_cond, &_lock);
        }
        T ret = _q.front();
        _q.pop();
        if (_q.size() < low_water)
            pthread_cond_broadcast(&_p_cond);
        pthread_mutex_unlock(&_lock);
        return ret;
    }

    ~BlockQueue()
    {
        pthread_mutex_destroy(&_lock);
        pthread_cond_destroy(&_p_cond);
        pthread_cond_destroy(&_c_cond);
    }

public:
    pthread_mutex_t _lock;
    pthread_cond_t _p_cond;
    pthread_cond_t _c_cond;

private:
    std::queue<T> _q;
    static const size_t maxCap = N;
    static const int high_water = maxCap - (maxCap / 3);
    static const int low_water = maxCap / 3;
};